<?php

/**
 */
class SRDO_Type {
	public $type;

	public function __construct($type, $sql = null, $fk = null) {
		$this->type = $type;
		if ( $sql ) {
			$this->sql($sql, $fk);
		}
	}	

	/**
	 * Set SQL/FK SQL for this type
	 */
	public function sql($sql, $fk = null) {
		SRDO::$config['type'][$this->type]['sql'] = array('pk' => $sql);
		
		if ( $fk ) {
			SRDO::$config['type'][$this->type]['sql']['fk'] = $fk;
		}
		
		if ( preg_match('/^([a-z0-9]+)(?:\(([0-9,]+)\))?\s+.*(?:DEFAULT\s+([\'"])?(.*)\3)?$/Ui', $sql, $m) ) {
			SRDO::$config['type'][$this->type]['cast'] = strtoupper($m[1]);
			if ( $m[2] ) {
				$this->set('size', $m[2]);
			}
			if ( $m[4] ) {
				$this->set('default', $m[4]);
			}
		}
	}
	
	/** 
	 * Set a key/value pair
	 */
	public function set($k, $v) {
		SRDO::$config['type'][$this->type]['var'][$k] = $v;
	}

	/**
	 * Get the PK SQL statement (for generating SQL)
	 */
	public function getSQL($type) {
		return SRDO::$config['type'][$type]['sql']['pk'];
	}

	/**
	 * Get FK SQL statement
	 */
	public function getFkSQL($type) {
		return SRDO::$config['type'][$type]['sql'][ (isset(SRDO::$config['type'][$type]['sql']['fk']) ? 'fk' : 'pk') ];
	}

	/** 
	 * Prepares a value based upon it's type
	 */
	public function prepareSQL($type, $value) {
		if ( is_a($value, 'SRDO_SQL') ) {
			return $value->sql;
		} elseif ( strtolower($value)  == 'null' ) {
			return 'NULL';
		}

		if ( isset(SRDO::$config['type'][$type]) ) {
			switch ( SRDO::$config['type'][$type]['cast'] ) {
				case 'VARCHAR':
				case 'CHAR':
				case 'TEXT':
				case 'DATETIME':
				case 'TIMESTAMP':
				case 'TIME':
				case 'YEAR':
				case 'DATE':
				case 'TINYTEXT':
				case 'MEDIUMTEXT':
				case 'LONGTEXT':
				case 'ENUM':
				case 'SET':
					$value = addslashes($value);
					return "'{$value}'";
				case 'TINYINT':
				case 'INT':
				case 'SMALLINT':
				case 'MEDIUMINT':
				case 'BIGINT':
					return (int)$value;
				case 'DECIMAL':
				case 'DOUBLE':
				case 'FLOAT':
					return (float)$value;
				case 'TINYBLOB':
				case 'BLOB':
				case 'MEDIUMBLOB':
				case 'LONGBLOB':
					return "'" . base64_encode($value) . "'";

				default:
					SRDO::error("RDO_Type:prepareSQL($type, ...): Unknown cast type '" . SRDO::$config['type'][$type]['cast'] . "'");
			}
		}

		return $value;
	}
}